<template>
  <div id="toolBar">
    <button @click="addsingleLayer">单瓦片</button>
    <button @click="addLayer">多瓦片</button>

    <button @click="getInfo">信息查询</button>
    <button>临时图层</button>
  </div>
</template>

<script setup lang="ts">
import { useStore } from "vuex";
import { state } from "../store";
import { unlistenByKey, EventsKey } from "ol/events";
import ImageLayer from "ol/layer/Image";
import ImageWMS from "ol/source/ImageWMS";
import TileWMS from "ol/source/TileWMS";
import TileLayer from "ol/layer/Tile";
const store = useStore();
let mapClickEvt: EventsKey | undefined;

let singleLayer: ImageLayer<ImageWMS>;
let layer: TileLayer<TileWMS>;
const addsingleLayer = () => {
  const { map }: state = store.state;
  if (singleLayer) {
    singleLayer.setVisible(!singleLayer.getVisible());
    return;
  }
  singleLayer = new ImageLayer({
    source: new ImageWMS({
      ratio: 1,
      url: "http://192.168.1.147:8080/geoserver/China/wms",
      params: {
        LAYERS: "China:xzq",
        VERSION: "1.1.1",
        FORMAT: "image/png",
        STYLES: "",
      },
    }),
  });
  map.addLayer(singleLayer);
};

const addLayer = () => {
  const { map }: state = store.state;
  if (layer) {
    layer.setVisible(!layer.getVisible());
    return;
  }
  layer = new TileLayer({
    source: new TileWMS({
      url: "http://192.168.1.147:8080/geoserver/China/wms",
      params: {
        LAYERS: "China:xzq",
        VERSION: "1.1.1",
        FORMAT: "image/png",
        STYLES: "",
      },
    }),
  });
  map.addLayer(layer);
};

function getInfo() {
  const { map }: state = store.state;
  if (mapClickEvt) {
    unlistenByKey(mapClickEvt);
    mapClickEvt = undefined;
  }
  mapClickEvt = map.on("click", (evt) => {
    console.log(evt.coordinate);
  });
}
</script>

<style scoped lang="less">
#toolBar {
  position: absolute;
  height: 40px;
  line-height: 40px;
  background-color: #f5f5f5;
  left: 30px;
  top: 20px;
  padding: 0 10px;
  border-radius: 10px;
  box-shadow: 0 5px 10px #a3a1a1;
  button {
    margin: 0 3px;
    cursor: pointer;
  }
}
</style>